import hashlib
import json

from flask import Flask, render_template, request, redirect
from flask_cors import CORS
from requests import post

app = Flask(__name__)
app.config.from_pyfile('config.py')

CORS(app, supports_credentials=True, resources={r"/*", "*"})

def md5ify(str):
    md5 = hashlib.md5()
    md5.update(str.encode())
    return md5.hexdigest()

@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        try:
            id = int(request.form.get('id'))
            res = json.loads(post('/user/login', id=id, pwd=md5ify(request.form.get('pwd'))).text)
            if res['type'] == 'SUCCESS':
                return render_template('index.html', baseURL=app.config.get('BASE_URL'), id=id, token=res['result']['token'])
            else:
                return render_template('login.html', error=res['message'])
        except ValueError:
            pass
    return render_template('login.html')